package com.kofan.shelter.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.kofan.shelter.commons.util.common.KofanServiceImpl;
import com.kofan.shelter.api.constants.TokenConstants;
import com.kofan.shelter.api.entity.User;
import com.kofan.shelter.api.bean.CodeConstants;
import com.kofan.shelter.api.bean.JsonResult;

import com.kofan.shelter.api.bean.Token;
import com.kofan.shelter.commons.util.utils.SecurityUtils;
import com.kofan.shelter.commons.util.utils.TokenUtil;
import com.kofan.shelter.mapper.UserMapper;
import com.kofan.shelter.web.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class UserServiceImpl extends KofanServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private IUserService userService;

    @Resource
    private TokenUtil tokenUtil;

    @Override
    public JsonResult login(User user) {
        User one = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getUserName, user.getUserName()));
        if (Objects.isNull(one)) {
            return JsonResult.error("用户名或密码错误，登录失败");
        }
        boolean login = SecurityUtils.matchesPassword(user.getPassword(), one.getPassword());
        if (!login) {
            return JsonResult.error("用户名或密码错误，登录失败");
        }
        try {
            Token redisToken = new Token();
            redisToken.setUserId(one.getUserId());
            String token = tokenUtil.createToken(redisToken);
            Map<String, Object> map = new HashMap<>();
            map.put("user", one);
            map.put("Authorization", TokenConstants.TOKEN_HEAD +token);
            return JsonResult.success(map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JsonResult.error("用户名或密码错误，登录失败");
    }
}
